package com.cn.dai.filter;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cn.dai.common.ErrorEnum;
import com.cn.dai.common.JwtToken;

import com.cn.dai.common.R;
import com.cn.dai.common.JwtHolder;
import com.cn.dai.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.cn.dai.common.RedisKeyCommon.COMMIT_REPLAY;
import static com.cn.dai.common.RedisKeyCommon.LOGIN_TOKEN_KEY;

@Slf4j
@Component
public class LoginFilter implements Filter {
    private static final List<String> urlList = new ArrayList<>();
    private static final String AUTHORIZATION = "Authorization";
    private static final String BEARER = "Bearer";
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化操作
        log.info("-----------------------初始化请求路径-----------------------");
        Filter.super.init(filterConfig);
        urlList.add("/login/*");
        urlList.add("/test/*");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        //过滤操作
        for (String url : urlList){
            if (url.endsWith("/*")){
                url = url.substring(0,url.length()-2);
            }
            if (requestURI.contains(url)){
                // 放行请求，继续执行下一个过滤器或目标资源
                chain.doFilter(request, response);
                return;
            }
        }
        //不放行的，准备校验身份
        log.error("请求次数");
        //获取请求头-认证信息
        String auth = request.getHeader(AUTHORIZATION);
        if (StringUtils.isBlank(auth)){
            //前端携带的认证信息为空
            responseMessage(response,ErrorEnum.TOKEN_NULL);
            log.error("当前请求未认证");
            return;
        }
        if (auth.startsWith(BEARER)){
            //前端携带的认证信息不规范
            responseMessage(response,ErrorEnum.TOKEN_ERROR);
            log.error("当前请求认证信息不规范");
            return;
        }
        String tokenFront = auth.split(BEARER)[1];
        log.info("前端传入的token：{}",tokenFront);
        //解析前端token todo 进行异常捕获
        JwtToken jwtToken = jwtUtil.parseJwt(tokenFront);
        //redis获取token
        String redisToken = redisTemplate.opsForValue().get(LOGIN_TOKEN_KEY + jwtToken.getId() + jwtToken.getName()).toString();
        if (StringUtils.isBlank(redisToken)){
            responseMessage(response,ErrorEnum.TOKEN_NULL);
            log.error("当前请求未认证");
            return;
        }
        if (tokenFront.equals(redisToken)){
            responseMessage(response,ErrorEnum.TOKEN_ANOTHER_ERROR);
            log.error("在其他地方登录");
            return;
        }
        //同一个用户2秒内防重复提交
        LocalDateTime now = LocalDateTime.now();
        now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:ss"));
        String replayRedisKey = COMMIT_REPLAY+requestURI+jwtToken.getId()+now;
        String replayRedisValue = String.valueOf(redisTemplate.opsForValue().get(replayRedisKey));
        if ("null".equals(replayRedisValue) || StringUtils.isNotBlank(replayRedisValue)){
            responseMessage(response,ErrorEnum.COMMIT_REPLAY);
            log.error("请勿重复点击");
            return;
        }
        //TODO 使用redis限制某一个接口流量
        JwtHolder.setLocal(jwtToken);
        //放重复redis占位
        redisTemplate.opsForValue().set(replayRedisKey,"1");
        chain.doFilter(request, response);
        //TODO 处理响应

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        //销毁操作
    }
    private void responseMessage(HttpServletResponse response,ErrorEnum errorEnum) throws IOException{
        //前端携带的认证信息为空
        response.setHeader("Content-Type","application/json;charset=utf-8");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(R.fail(errorEnum.getCode(),errorEnum.getMessage())));
    }
    private boolean commitReplay(String key){
        LocalDateTime now = LocalDateTime.now();
        now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:ss"));
        String replayRedisKey = key+now;
        String replayRedisValue = String.valueOf(redisTemplate.opsForValue().get(replayRedisKey));
        return "null".equals(replayRedisValue) || StringUtils.isNotBlank(replayRedisValue);
    }
}
